<?php

require_once 'config.php';

function user_oauth() {
	require_once 'OAuth.php';
	session_start();
	setCookie('Oauth', 'oauth', time()+3600*24*1000);

	if ($oauth_token = $_GET['oauth_token']) {
		$params = array('oauth_verifier' => $_GET['oauth_verifier']);
		$response = oauth_process('https://api.twitter.com/oauth/access_token', $params);
		parse_str($response, $token);
		setCookie('up', $token['oauth_token'].'|'.$token['oauth_token_secret'],time()+3600*24*1000);
		unset($_SESSION['oauth_request_token_secret']);
		setCookie('l', 'OK', time()+3600*24*1000);
		header('Location: '. BASE_URL);
		exit();

	} else {
		$params = array('oauth_callback' => BASE_URL);
		$response = oauth_process('https://api.twitter.com/oauth/request_token', $params);
		parse_str($response, $token);
		$_SESSION['oauth_request_token_secret'] = $token['oauth_token_secret'];
		$authorise_url = 'https://api.twitter.com/oauth/authorize?oauth_token='.$token['oauth_token'];
		header("Location: $authorise_url");
	}
}

function user_oauth_sign(&$url, &$args = false) {
	require_once 'OAuth.php';
	$method = $args !== false ? 'POST' : 'GET';

	if (preg_match_all('#[?&]([^=]+)=([^&]+)#', $url, $matches, PREG_SET_ORDER)) {
		foreach ($matches as $match){$args[$match[1]] = $match[2];}
			$url = substr($url, 0, strpos($url, '?'));
	}

	$sig_method = new OAuthSignatureMethod_HMAC_SHA1();
	$consumer = new OAuthConsumer(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET);
	$token = NULL;

	if ((isset($_GET['oauth_token']) && ($oauth_token = $_GET['oauth_token'])) && $_SESSION['oauth_request_token_secret']) {
		$oauth_token_secret = $_SESSION['oauth_request_token_secret'];
	} else {
		list($oauth_token, $oauth_token_secret) = explode('|', $_COOKIE['up']);
	}

	if ($oauth_token && $oauth_token_secret) {
		$token = new OAuthConsumer($oauth_token, $oauth_token_secret);
	}

	$request = OAuthRequest::from_consumer_and_token($consumer, $token, $method, $url, $args);
	$request->sign_request($sig_method, $consumer, $token);

	switch ($method) {
	case 'GET':
		$url = $request->to_url();
		$args = false;
		return;
	case 'POST':
		$url = $request->get_normalized_http_url();
		$args = $request->to_postdata();
		return;
	}
}

function oauth_process($url, $post_data = false) {
	if ($post_data === true) $post_data = array();
	user_oauth_sign($url, $post_data);

	$ch = curl_init($url);
	if($post_data !== false) {
		curl_setopt ($ch, CURLOPT_POST, true);
		curl_setopt ($ch, CURLOPT_POSTFIELDS, $post_data);
	}

	curl_setopt($ch, CURLOPT_VERBOSE, 0);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_TIMEOUT, 10);
	curl_setopt($ch, CURLOPT_USERAGENT, 'kwestion');
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	$response = curl_exec($ch);
	$response_info=curl_getinfo($ch);
	curl_close($ch);
	if(intval($response_info['http_code']) == 200) {
		$json = json_decode($response);
		if ($json) return $json;
		return $response;
	}else{
		setCookie('Oauth', 'oauth', time()-3600*24*1000);
		header('Location: '. BASE_URL);
	}
}

function user_type(){
	return isset($_COOKIE["Oauth"]) && $_COOKIE['Oauth'] == 'oauth';
}

function twitter_process($url, $post_data = false) {
	return raw_twitter_process(getU(),getP(),$url,$post_data);
}

function raw_twitter_process($u,$p,$url,$post_data = false){
	if($post_data === true) $post_data = array();
	$file = false;
	if(isset($post_data['file'])){
		$file = $post_data['file'];
		//echo 'here';
		unset($post_data['file']);
	}

	if (user_type() && ( strpos($url, '/twitter.com') !== false || strpos($url, 'api.twitter.com') !== false) ) {
		user_oauth_sign($url, $post_data);
	}

	$ch = curl_init($url);

	if($post_data !== false) {
		curl_setopt ($ch, CURLOPT_POST, 1);
		curl_setopt ($ch, CURLOPT_POSTFIELDS, $post_data);
		if($file!==false){
			curl_setopt($ch, CURLOPT_POSTFIELDS, $file);
		}
	}

	if (!user_type())
		curl_setopt($ch, CURLOPT_USERPWD, $u.':'.$p);

	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
	curl_setopt($ch, CURLOPT_HEADER, FALSE);
	curl_setopt($ch, CURLOPT_VERBOSE, 0);
	curl_setopt($ch, CURLOPT_TIMEOUT, 10);
	curl_setopt($ch, CURLOPT_USERAGENT, 'kwestion');
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

	$response = curl_exec($ch);
	$response_info=curl_getinfo($ch);
	curl_close($ch);

	//echo $response;
	if(intval( $response_info['http_code'])==200){

		$json = json_decode($response);
		if(!($json===false)){
			return $json;
		}
		else{
			return false;
		}
	}
	else{
		return false;
	}
}


function oAuthRequest($url, $method, $parameters , $multi = false) {
	require_once 'OAuth.php';

	if (preg_match_all('#[?&]([^=]+)=([^&]+)#', $url, $matches, PREG_SET_ORDER)) {
		foreach ($matches as $match){$args[$match[1]] = $match[2];}
			$url = substr($url, 0, strpos($url, '?'));
	}

	$sig_method = new OAuthSignatureMethod_HMAC_SHA1();
	$consumer = new OAuthConsumer(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET);
	$token = NULL;

	if (($oauth_token = $_GET['oauth_token']) && $_SESSION['oauth_request_token_secret']) {
		$oauth_token_secret = $_SESSION['oauth_request_token_secret'];
	} else {
		list($oauth_token, $oauth_token_secret) = explode('|', $_COOKIE['up']);
	}

	if ($oauth_token && $oauth_token_secret) {
		$token = new OAuthConsumer($oauth_token, $oauth_token_secret);
	}

	$request = OAuthRequest::from_consumer_and_token($consumer, $token, $method, $url, $parameters);
	$request->sign_request($sig_method, $consumer, $token);

	$extheader = null;
	if($multi){
		$extheader = $request->to_header();
	}
	switch ($method) {
	case 'GET':
		return http($request->to_url(), 'GET');
	default:
		return http($request->get_normalized_http_url(), $method, $request->to_postdata($multi) , $multi, $extheader );
	}
}

function http($url, $method, $postfields = NULL , $multi = false, $extheader = false) {
	$http_info = array();
	$ci = curl_init();
	curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($ci, CURLOPT_HEADER, FALSE);
	curl_setopt($ci, CURLOPT_VERBOSE, 0);
	curl_setopt($ci, CURLOPT_TIMEOUT, 10);
	curl_setopt($ci, CURLOPT_USERAGENT, 'kwestion');

	switch ($method) {
	case 'POST':
		curl_setopt($ci, CURLOPT_POST, TRUE);
		if (!empty($postfields)) {
			curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
		}
		break;
	case 'DELETE':
		curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
		if (!empty($postfields)) {
			$url = "{$url}?{$postfields}";
		}
	}

	$header_array2=array('Expect: ');
	if( $multi )
		$header_array2 = array($extheader, "Content-Type: multipart/form-data; boundary=" . OAuthUtil::$boundary, "Expect: ");

	curl_setopt($ci, CURLOPT_URL, $url );
	curl_setopt($ci, CURLOPT_HTTPHEADER, $header_array2 );

	$response = curl_exec($ci);
	$http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
	curl_close ($ci);
	return $response;
}


function preg_match_one($pattern, $subject, $flags = NULL) {
	preg_match($pattern, $subject, $matches, $flags);
	return trim($matches[1]);
}

function parse_thread($html){
	$output = array();
	$html_tweets = explode('</li>', $html);
	foreach ($html_tweets as $tweet) {
		$id = preg_match_one('#msgtxt(\d*)#', $tweet);
		if (!$id) continue;
		$output[] = (object) array(
			'id' => $id,
			'text' => strip_tags(preg_match_one('#</a>: (.*)</span>#', $tweet)),
			'source' => preg_match_one('#>from (.*)</span>#', $tweet),
			'from' => (object) array(
				'id' => preg_match_one('#profile_images/(\d*)#', $tweet),
				'screen_name' => preg_match_one('#twitter.com/([^"]+)#', $tweet),
				'profile_image_url' => preg_match_one('#src="([^"]*)"#' , $tweet),
			),
			'to' => (object) array(
				'screen_name' => preg_match_one('#@([^<]+)#', $tweet),
			),
			'created_at' => str_replace('about', '', preg_match_one('#info">\s(.*)#', $tweet)),
		);
	}
	return $output;
}


function processstatuses($statuses){
	$newstatuses = array();
	//var_dump($statuses);
	if(!is_array($statuses))
		return array();
	foreach($statuses as $t){
		$newstatuses[] = processstatus($t);
	}
	return $newstatuses;
}

function processstatus($status){
	$text = $status->text;
	if(UNSHORTEN_URL){
		$text = unshorturl($text);
	}
	$text = twitter_parse_tags($text);
	$status->processedtext = $text; 
	return $status;
}

function twitter_parse_tags($input){
	$out = preg_replace('#(\w+?://[\w\#$%&~/.\-;:=,?\[\]+]*)(?<![.,])#', '<a href="$1" target="_blank">$1</a>', $input);
	$out = twitter_photo_replace($out);
	return $out;
}

function twitter_photo_replace($text) {
	$images = array();
	$tmp = strip_tags($text);

	$services = array(
		'#youtube\.com\/watch\?v=([_-\d\w]+)#i'   => 'http://i.ytimg.com/vi/%s/1.jpg',
		'#youtu\.be\/([_-\d\w]+)#i'               => 'http://i.ytimg.com/vi/%s/1.jpg',
		'#qik\.ly\/([_-\d\w]+)#i'                 => 'http://qik.ly/%s.jpg',
		'#twitpic\.com\/([\d\w]+)#i'              => 'http://twitpic.com/show/thumb/%s',
		'#twitgoo\.com\/([\d\w]+)#i'              => 'http://twitgoo.com/show/thumb/%s',
		'#hellotxt\.com\/i\/([\d\w]+)#i'          => 'http://hellotxt.com/image/%s.s.jpg',
		'#ts1\.in\/(\d+)#i'                       => 'http://ts1.in/mini/%s',
		'#moby\.to\/\?([\w\d]+)#i'                => 'http://moby.to/%s:square',
		'#mobypicture\.com\/\?([\w\d]+)#i'        => 'http://mobypicture.com/?%s:square',
		'#twic\.li\/([\w\d]{2,7})#'               => 'http://twic.li/api/photo.jpg?id=%s&size=small',
		'#tweetphoto\.com\/(\d+)#'                => 'http://api.plixi.com/api/tpapi.svc/imagefromurl?url=http://tweetphoto.com/%s',
		'#plixi\.com\/p\/(\d+)#'                  => 'http://api.plixi.com/api/tpapi.svc/imagefromurl?url=http://plixi.com/p/%s&size=small',
		'#phz\.in\/([\d\w]+)#'                    => 'http://api.phreadz.com/thumb/%s?t=code',
		'#imgur\.com\/([\w]{5})[\s\.ls][\.\w]*#i' => 'http://imgur.com/%ss.png',
		'#imgur\.com\/gallery\/([\w]+)#i'         => 'http://imgur.com/%ss.png',
		'#brizzly\.com\/pic\/([\w]+)#i'           => 'http://pics.brizzly.com/thumb_sm_%s.jpg',
		'#img\.ly\/([\w\d]+)#i'                   => 'http://img.ly/show/thumb/%s',
		'#picplz\.com\/.*?\/pic\/([\d\w\.]+)#'              => 'http://picplz.com/%s/thumb',
		'#picplz\.com\/([\d\w\.]+)#'              => 'http://picplz.com/%s/thumb',
		'#pk\.gd\/([\d\w]+)#i'                    => 'http://img.pikchur.com/pic_%s_s.jpg',
		'#pikchur\.com\/([\d\w]+)#i'              => 'http://img.pikchur.com/pic_%s_s.jpg',
		'#znl\.me\/([\d\w]+)#'                    => 'http://www.zannel.com/webservices/content/%s/Image-164x123-JPG.jpg',
		'#yfrog\.com\/([\d\w]+)#'                 => 'http://yfrog.com/%s:small'
	);

	// Loop through each service and show images for matching URLs
	foreach ($services as $pattern => $thumbnail_url) {
		if (preg_match_all($pattern, $tmp, $matches, PREG_PATTERN_ORDER) > 0) {
			foreach ($matches[1] as $key => $match) {
				$images[] = '<a href="http://'.$matches[0][$key].'" target="_blank"><img src="'.sprintf($thumbnail_url, $match).'" /></a>';
			}
			break;
		}
	}

	// Twitxr is handled differently because of their folder structure
	if (preg_match_all('#twitxr.com/[^ ]+/updates/([\d]+)#', $tmp, $matches, PREG_PATTERN_ORDER) > 0) {
		foreach ($matches[1] as $key => $match) {
			$thumb = 'http://twitxr.com/thumbnails/'.substr($match, -2).'/'.$match.'_th.jpg';
			$images[] = '<a href="http://'.$matches[0][$key].'" target="_blank">"<img src="'.$thumb.'" /></a>';
		}
	}

	// AudioBoo is handled differently because we link directly to an MP3, not an image
	if (preg_match_all('#boo.fm/b([\d]+)#', $tmp, $matches, PREG_PATTERN_ORDER) > 0) {
		foreach ($matches[1] as $key => $match) {
			$images[] = "<a href='http://{$matches[0][$key]}.mp3' target='_blank'>[点击此处听音乐]</a>";
		}
	}

	// match phz.in (short phreadz)  urls
	if (preg_match_all('#phz.in/([\d\w]+)#', $tmp, $matches, PREG_PATTERN_ORDER) > 0){
		foreach ($matches[1] as $match){
			//Images from Phreadz aren't always suitable for mobile, so we use http://tinysrc.mobi/ to convert them
			$thumb = "http://i.tinysrc.mobi/x50/http://api.phreadz.com/thumb/" . $match . "?t=code";
			$images[] = '<a href="http://phz.in/'. $match.'" target="_blank"><img src="'.$thumb.'" /></a>';
		}
	}
	if (empty($images)) return $text;
	return implode('<br />', $images).'<br />'.$text;
}

function unshorturl($text){
	$urlregs = array();
	$urlregs[] ='/t\.co\/([a-z0-9]*)/i';
	$urlregs[] ='/tinyurl\.com\/([a-z0-9]{5}[a-z0-9]*)/i';
	$urlregs[] ='/bit\.ly\/([a-z0-9]{5}[a-z0-9]*)/i';
	$urlregs[] ='/twurl\.nl\/([a-z0-9]{5}[a-z0-9]*)/i';
	$urlregs[] ='/j\.mp\/([a-z0-9]{5}[a-z0-9]*)/i';
	$urlregs[] ='/retwt\.me\/([a-z0-9]{5}[a-z0-9]*)/i';
	$urlregs[] ='/ff\.im\/-([a-z0-9]{5}[a-z0-9]*)/i';
	$urlregs[] ='/tr\.im\/([a-z0-9]{5}[a-z0-9]*)/i';
	$urlregs[] ='/htxt\.it\/([a-z0-9]{4}[a-z0-9]*)/i';
	$urlregs[] ='/aa\.cx\/([a-z0-9]*)/i';
	$urlregs[] ='/2\.ly\/([a-z0-9]*)/i';
	//$text .='!!!';
	foreach($urlregs as $urlreg) {
		if(preg_match($urlreg,$text,$match)){
			$request = 'http://api.unshort.me/?r='.urlencode('http://' . $match[0]);
			$tmpstr = processcurl($request);
			$url = substr($tmpstr,13+strpos($tmpstr,"<resolvedURL>"),strpos($tmpstr,"</resolvedURL>") - 13 - strpos($tmpstr,"<resolvedURL>"));
			$text = str_replace('http://'.$match[0], $url, $text);
		}
	}
	return $text;
}

function utf8_substr($str,$start){ 
	preg_match_all("/[x01-x7f]|[xc2-xdf][x80-xbf]|xe0[xa0-xbf][x80-xbf]|[xe1-xef][x80-xbf][x80-xbf]|xf0[x90-xbf][x80-xbf][x80-xbf]|[xf1-xf7][x80-xbf][x80-xbf][x80-xbf]/", $str, $ar);
	var_dump($ar);
	if(func_num_args() >= 3) { 
		$end = func_get_arg(2); 
		return join("",array_slice($ar[0],$start,$end)); 
	} else { 
		return join("",array_slice($ar[0],$start)); 
	}

}

function utf8_strlen($str){
	preg_match_all("/[x01-x7f]|[xc2-xdf][x80-xbf]|xe0[xa0-xbf][x80-xbf]|[xe1-xef][x80-xbf][x80-xbf]|xf0[x90-xbf][x80-xbf][x80-xbf]|[xf1-xf7][x80-xbf][x80-xbf][x80-xbf]/", $str, $ar);
	var_dump($ar);

	return count($ar[0]);
}

function processcurl($url,$postargs=false){
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_VERBOSE, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	$response = curl_exec($ch);
	$responseInfo=curl_getinfo($ch);
	curl_close($ch);
	if( intval( $responseInfo['http_code'] ) == 200 )
		return $response;    
	else
		return false;
}

function getU(){
	if(isset($_COOKIE['un']))
		return trim($_COOKIE['un']);
	return '';
}

function getP(){
	if(isset($_COOKIE['up']))
		return trim($_COOKIE['up']);
	return '';
}

function isLogin(){
	if(isset($_COOKIE['l'])){
		return $_COOKIE['l'] == 'OK';
	}
	return false;
}

function compress($content){ 
	if( !headers_sent() && extension_loaded("zlib") && strstr($_SERVER["HTTP_ACCEPT_ENCODING"],"gzip")){
		$content = gzencode($content." \n",1);
		header("Content-Encoding: gzip"); 
		header("Vary: Accept-Encoding");
		header("Content-Length: ".strlen($content));
	}
	return $content;
}

?>
